package com.castile.secondkill.controller;

import com.castile.secondkill.error.EmBusinessError;
import com.castile.secondkill.exception.BusinessException;
import com.castile.secondkill.response.CommonResponse;
import com.castile.secondkill.response.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 基础的Controller，用于统一异常处理
 *
 * @author Hongliang Zhu
 * @create 2023-03-05 21:23
 */
@Controller
public class BaseController {
    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    //    public static final String CONTEN
    @ExceptionHandler({Exception.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.OK) // 返回一个200 的代码
    public Object handleException(HttpServletRequest request, Exception ex) {

        Map<String, Object> responseData = new HashMap<>(16);
        if (ex instanceof BusinessException) {
            BusinessException businessException = (BusinessException) ex;
            responseData.put("errCode", businessException.getErrorCode());
            responseData.put("errMsg", businessException.getErrMsg());
            logger.error("errCode={}, message = {}", businessException.getErrorCode(), businessException.getErrMsg());
        } else {
            responseData.put("errCode", EmBusinessError.UNKNOWN_ERROR.getErrorCode());
            responseData.put("errMsg", EmBusinessError.UNKNOWN_ERROR.getErrMsg());
            logger.error("have an exception", ex);
        }
        return CommonResponse.create(responseData, Status.FAILED);
    }
}
